package com.zuowei.ycy.user.ui.login;

import android.content.Context;
import android.graphics.drawable.Animatable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.CountDownTimer;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.and.yzy.frame.util.AppUtils;
import com.and.yzy.frame.util.DensityUtils;
import com.and.yzy.frame.util.RetrofitUtils;
import com.and.yzy.frame.util.SPUtils;
import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.controller.BaseControllerListener;
import com.facebook.drawee.controller.ControllerListener;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.image.ImageInfo;
import com.zuowei.ycy.R;
import com.zuowei.ycy.user.http.OpenPage;
import com.zuowei.ycy.ui.BaseAty;
import com.zuowei.ycy.user.ui.MainAty;
import com.zuowei.ycy.user.util.AppJsonUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;


/**
 * 启动页
 */
public class FirstAty extends BaseAty {

    @Bind(R.id.iv_wecome)
    SimpleDraweeView mImageView;
    @Bind(R.id.convenientBanner)
    ConvenientBanner mBanner;

    boolean isfirst = false;
    @Bind(R.id.tv_time)
    TextView mTvTime;
    @Bind(R.id.ll_time)
    LinearLayout mLlTime;
    @Bind(R.id.rl_page)
    RelativeLayout mRlPage;
    TempCount tempCount;

    @Override
    public int getLayoutId() {
        return R.layout.first_layout;
    }

    @Override
    public void initData() {

        //判断版本
        SPUtils spUtils = new SPUtils("code");

        int code = (int) spUtils.get("code", 0);
        Log.i("result", "code==" + code);
        if (AppUtils.getVersionCode(this) > code) {
            //开启引导页
            isfirst = true;
            final MyCount myCount = new MyCount(12000, 1000);

            Handler handler = new Handler();

            handler.postDelayed(new Runnable() {
                @Override
                public void run() {

                    mBanner.setVisibility(View.VISIBLE);
                    mRlPage.setVisibility(View.GONE);

                    myCount.start();
                }
            }, 2000);


            List<Drawable> mBannerImages = new ArrayList<>();

            mBannerImages.add(getResources().getDrawable(R.drawable.ic_01));
            mBannerImages.add(getResources().getDrawable(R.drawable.ic_02));
            mBannerImages.add(getResources().getDrawable(R.drawable.ic_03));
          mBanner.setCanLoop(false);
            mBanner.setPages(new CBViewHolderCreator<LocalHolderView>() {
                @Override
                public LocalHolderView createHolder() {
                    return new LocalHolderView();
                }
            }, mBannerImages)
                    .setPageIndicator(new int[]{R.drawable.yindao, R.drawable.yindao2}, DensityUtils.dp2px(this, 5))
                    .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL)
                    .setOnItemClickListener(new OnItemClickListener() {
                        @Override
                        public void onItemClick(int position) {

                            if (position == 2) {

                                myCount.cancel();
                                setHasAnimiation(false);

                                startActivity(MainAty.class, null);

                                setHasAnimiation(false);

                                finish();

                            }
                        }
                    })
            ;


            spUtils.put("code", AppUtils.getVersionCode(this));
        } else {
            isfirst = false;
            mBanner.setVisibility(View.GONE);
            mRlPage.setVisibility(View.VISIBLE);
            MyCount myCount = new MyCount(1500, 1000);
            myCount.start();


        }


        mLlTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (tempCount != null) {

                    tempCount.cancel();
                }


                startActivity(MainAty.class, null);
                setHasAnimiation(false);

                finish();


            }
        });
    }

    @Override
    public void requestData() {


    }


    private class MyCount extends CountDownTimer {

        /**
         * @param millisInFuture    The number of millis in the future from the call
         *                          to {@link #start()} until the countdown is done and {@link #onFinish()}
         *                          is called.
         * @param countDownInterval The interval along the way to receive
         *                          {@link #onTick(long)} callbacks.
         */
        public MyCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {


        }

        @Override
        public void onFinish() {
            setHasAnimiation(false);
            if (isfirst) {
                startActivity(MainAty.class, null);
                setHasAnimiation(false);

                finish();
            } else {

                //下载开启页
                doHttp(RetrofitUtils.createApi(OpenPage.class).getPic(), 1);


            }


        }
    }

    private class TempCount extends CountDownTimer {

        /**
         * @param millisInFuture    The number of millis in the future from the call
         *                          to {@link #start()} until the countdown is done and {@link #onFinish()}
         *                          is called.
         * @param countDownInterval The interval along the way to receive
         *                          {@link #onTick(long)} callbacks.
         */
        public TempCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            if (mTvTime != null) {
                mTvTime.setText(millisUntilFinished / 1000 + "");
            }

        }

        @Override
        public void onFinish() {
            setHasAnimiation(false);

            startActivity(MainAty.class, null);
            setHasAnimiation(false);

            finish();


        }
    }


    @Override
    public void onSuccess(String result, Call<ResponseBody> call, Response<ResponseBody> response, int what) {

        String pic = AppJsonUtil.getString(result, "picture");

        ControllerListener listener = new BaseControllerListener<ImageInfo>() {
            @Override
            public void onFailure(String id, Throwable throwable) {
                super.onFailure(id, throwable);
                startActivity(MainAty.class, null);
                setHasAnimiation(false);

                finish();
            }

            @Override
            public void onFinalImageSet(String id, ImageInfo imageInfo, Animatable animatable) {
                super.onFinalImageSet(id, imageInfo, animatable);

                mLlTime.setVisibility(View.VISIBLE);
                tempCount = new TempCount(4000, 1000);
                tempCount.start();

            }
        };


        DraweeController controller = Fresco.newDraweeControllerBuilder()
                .setControllerListener(listener)
                .setUri(Uri.parse(pic))
                .build();
        mImageView.setController(controller);


        super.onSuccess(result, call, response, what);
    }

    class LocalHolderView implements Holder<Drawable> {

        private ImageView imageView;

        @Override
        public View createView(Context context) {
            imageView = new ImageView(context);

            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            return imageView;
        }

        @Override
        public void UpdateUI(Context context, final int position, Drawable data) {
            imageView.setImageDrawable(data);

        }
    }
}
